<template>
  <div class="login-page mx-auto p-3 w-330">
    <h5 class="my-4 text-center">登录到者也</h5>
    <ValidateFrom @form-submit="onFormSubmit"
                  ref="formRef">
      <div class="mb-3">
        <label class="form-label">邮箱地址</label>
        <ValidateInput :rules="emailRules"
                       v-model="emailVal"
                       placeholder="请输入邮箱地址"
                       type="text">
        </ValidateInput>
        {{ emailVal }}
      </div>
      <div class="mb-3">
        <label class="form-label">密码</label>
        <ValidateInput :rules="passwordRules"
                       v-model="passwordVal"
                       placeholder="请输入密码"
                       type="password">
        </ValidateInput>
      </div>
      <template #submit>
        <button type="submit"
                class="btn btn-primary btn-block btn-large">登录</button>
      </template>
    </ValidateFrom>
  </div>

</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
import { useStore } from 'vuex'
import 'bootstrap/dist/css/bootstrap.min.css'
// useRouter定义路由的行为
import { useRouter } from 'vue-router'
import ValidateInput, { RulesProp } from '../components/ValidateInput.vue'
import ValidateFrom from '../components/ValidateForm.vue'
import createMessage from '../components/createMessage'


export default defineComponent({
  name: 'Login',
  components: {
    ValidateInput,
    ValidateFrom
  },
  setup() {
    const router = useRouter()
    // 邮箱地址的验证
    const emailVal = ref('')
    const emailRules: RulesProp = [
      { type: 'requied', message: '电子邮箱不能为空' },
      { type: 'email', message: '请输入正确的电子邮箱格式' },
      { type: 'range', message: '请输入正确的电子邮箱长度' },
    ]
    // 密码的验证
    const passwordVal = ref('')
    const passwordRules: RulesProp = [
      { type: 'requied', message: '密码不能为空' },
      {
        type: 'range',
        min: { message: '您的密码至少包括六位，且不能含有空格', length: 6 },
        max: { message: '您的密码最多有十六位，且不能含有空格', length: 16 },
      }
    ]

    const store = useStore()

    // 提交
    const onFormSubmit = (result: boolean) => {
      if (result) {
        const payload = {
          email: emailVal.value,
          password: passwordVal.value
        }
        console.log(emailVal.value, passwordVal.value);
        store.dispatch('loginAndFetch', payload).then(() => {
          createMessage('登录成功!2秒后跳转到主页...', 'success', 1000)
          setTimeout(() => {
            router.push('/')
          }, 2000);
        }).catch(e => {
          console.log(e);
        })
      }
    }
    return {
      emailVal,
      emailRules,
      passwordVal,
      passwordRules,
      onFormSubmit,
    }
  }

}

)
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.w-330 {
  width: 330px;
}
</style>
